package routes

import (
	"power/core/common/errorcode"
	"power/core/common/types"
	"strconv"
	"strings"
	"time"

	"github.com/RocksonZeta/irisx"
	"github.com/RocksonZeta/wrap/errs"
	"gopkg.in/guregu/null.v4"
)

func Check(c *irisx.Context) {
	fieldErrors := c.ParamErrors()
	if len(fieldErrors) > 0 {
		e := errs.NewUserError(errorcode.ParamError, "request parameter error")
		e.Data = fieldErrors
		panic(e)
	}
}

func CheckBodyStringNull(c *irisx.Context, field string) null.String {
	str := strings.TrimSpace(c.FormValue(field))
	return null.NewString(str, str != "")
}
func CheckBodyIntNull(c *irisx.Context, field string) null.Int {
	str := strings.TrimSpace(c.FormValue(field))
	if "" == str {
		return null.NewInt(0, false)
	}
	i, err := strconv.ParseInt(str, 10, 64)
	if err != nil {
		c.AddParamError(field, err.Error())
	}
	return null.NewInt(i, err == nil)
}

func CheckBodyTimeNull(c *irisx.Context, field, format string) null.Time {
	return null.NewTime(CheckBodyTime(c, field, format))
}

//NullDate format 2006-01-02 15:04:05
func CheckBodyTime(c *irisx.Context, field, format string) (time.Time, bool) {
	str := strings.TrimSpace(c.FormValue(field))
	if str == "" {
		return time.Time{}, false
	}
	loc, _ := time.LoadLocation("Local")
	if "" == format {
		format = "2006-01-02"
	}
	t, err := time.ParseInLocation(format, str, loc)
	if err != nil {
		c.AddParamError(field, err.Error())
	}
	return t, err == nil
}

func CheckSignin(c *irisx.Context) {
	if !c.HasSignin() {
		e := errs.NewUserError(errorcode.UserNoSignin, "Please signin.")
		panic(e)
	}
}

func Page(c *irisx.Context, items interface{}, total int64, pageSize, pageIndex int) {
	c.Ok(types.NewPage(items, int(total), pageSize, pageIndex))
}
